<template>
	<view class="gy-parse">
		<rich-text :selectable="true" :nodes="text" @itemclick="itemClickFn" />
	</view>
</template>

<script lang="ts" setup>
	
	import {
		ref,
		watch
	} from 'vue';
	
	const props = defineProps({
	    content: {
	    	type: String,
			default: ""
	    }
	});
	
	const text = ref("");
	
	function itemClickFn(event: any){
		// console.log(event);
	}
	
	function formatRichText(html: string){
	    let newContent= html.replace(/<img[^>]*>/gi, (match: any, capture: any) => {
	        match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
	        match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
	        match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
	        return match;
	    });
		newContent = newContent.replace(new RegExp("<p><br></p>", "gi"), '');
	    newContent = newContent.replace(/style="[^"]+"/gi, (match: any, capture: any) => {
	        match = match
	        .replace(/<p>/gi, '<p class="p_class">')
	        .replace(/width:[^;]+;/gi, 'max-width:100%;')
	        .replace(/width:[^;]+;/gi, 'max-width:100%;');
	        return match;
	    });
	    newContent = newContent.replace(/<br[^>]*\/>/gi, "");
	    newContent = newContent.replace(/<a>/gi, '<a class="gy-parse-a "');
	    newContent = newContent.replace(/<li>/gi, '<li class="gy-parse-li "');
	    newContent = newContent.replace(/\<p/gi, '<p class="gy-parse-p "');
	    newContent = newContent.replace(/\<span/gi, '<span class="gy-parse-span "');
	    newContent = newContent.replace(/\<img/gi, '<img class="gy-parse-img" ');
		newContent = newContent.replace(/\<video/gi, '<video class="gy-parse-video" ');
		// newContent = newContent.replace(/\<table/gi, '<table border="1" class="gy-parse-table" ');
		// newContent = newContent.replace(/\<tbody/gi, '<tbody class="gy-parse-tbody" ');
		// newContent = newContent.replace(/\<tr/gi, '<tr class="gy-parse-tr" ');
		// newContent = newContent.replace(/\<td/gi, '<td class="gy-parse-td" ');
	    return newContent;
	}
	
	watch(() => props.content, (newVal: string, oldVal: string) => {
		text.value = formatRichText(props.content);
	}, {immediate: true})
	
</script>

<style lang="scss" scoped>
	.gy-parse{
		word-wrap: break-word;
		:deep(.gy-parse-p){
			font-size: 32rpx;
			line-height: 38rpx;
			margin: 20rpx 0;
		}
		:deep(.gy-parse-img){
			display: block;
			max-width: 100%;
			height: auto;
			margin: 10px 0;
			border-radius: 10px;
		}
		:deep(.gy-parse-video){
			display: block;
			max-width: 100%;
			height: auto;
			margin: 10px 0;
		}
		:deep(.gy-parse-table){
			width: 100%;
			// border: 1px solid #CBCFDF;
		}
		:deep(.gy-parse-tbody){
			
		}
		:deep(.gy-parse-tr .gy-parse-td){
			padding: 10px;
			background-color: #F2F2F2;
		}
		:deep(.gy-parse-tr .gy-parse-td:nth-child(1)){
			text-align: center;
		}
		:deep(.gy-parse-p:first-child){
			margin-top: 0;
		}
	}
</style>